/**
 * 询价.COM v1.0.0
 * http://xun-jia.com/
 *
 * Copyright (c) 2009 
 * 四川漾天空网络科技有限公司
 * 成都市天府软件园A3栋2楼
 *
 */
package com.xunjia.registion.action;

import java.io.File;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.Action;
import com.xunjia.action.XunJiaActionSupport;
import com.xunjia.json.JSONArray;
import com.xunjia.json.JSONObject;
import com.xunjia.util.Constants;
import com.xunjia.util.CookieUtil;
import com.xunjia.util.DateUtils;
import com.xunjia.util.HttpSessionUtils;
import com.xunjia.util.PatternUtils;
import com.xunjia.util.StringUtil;
import com.yam.michael.hibernate.pojo.AdvActivity;
import com.yam.michael.hibernate.pojo.AdvPosition;
import com.yam.michael.hibernate.pojo.Company;
import com.yam.michael.hibernate.pojo.HyperlinkAdvInfo;
import com.yam.michael.hibernate.pojo.Keywords;
import com.yam.michael.hibernate.pojo.KeywordsAdvInfo;
import com.yam.michael.hibernate.pojo.UserInfo;
import com.yam.michael.service.IUserService;

/**
 * @author Mark
 * 
 * @Email Mark_yang@xun-jia.com
 * 
 * @Date 2009-4-3 上午09:01:07
 * 
 */
public class RegistionAction extends XunJiaActionSupport {
	// 用户登陆DAO
	private IUserService userService;
	// 日志
	private static final Logger logger = Logger.getLogger(RegistionAction.class);
	// 序列码
	private static final long serialVersionUID = 460285511762313018L;
	// 模块名称
	private static final String MODAL_NAME = "/registion";
	// 选择自定义每日广告预算
	private static final String CUSTOM_BUDGET_ON = "ON";
	/** 基本资料 */
	// 姓氏
	private String firstname;
	// 名字
	private String lastname;
	// 邮箱地址
	private String email;
	// 电话
	private String phone;
	// 移动电话
	private String mobile;
	// 公司统一编号
	private String serialnumber;
	// 公司全称
	private String corporationname;
	// 传真
	private String fax;
	// 城市
	private String city;
	// 地址
	private String address;
	// 邮编
	private String zip;
	// 确认邮件地址
	private String confirm_email;
	// 身份证
	private String idcard;
	// 用户注册类型
	private String type;

	/** 创建关键字广告 */
	// 自定义每日预算
	private String customBudget;
	// 预算
	private String budget;
	// 每月花费
	private String costPerMonth;
	// 宣传网页
	private String weblink;
	// 标题
	private String title;
	// 内容描述
	private String desc;
	// 关键字
	private String keywords;

	/** 创建图片广告 */
	// 广告位置
	private String position;
	// 文件保存路径
	private static final String FILE_SAVE_DIR = "file.saveDir";
	// 文件上传配置路径
	private static final String FILE_CONFIG_NAME = "fileupload";
	// 上传文件
	private File uploadimg;
	// 上传文件名称
	private String uploadimgFileName;
	// 上传文件类型
	private String uploadimgContentType;
	// 购买日期到
	private String todate;
	// 图片显示名称
	private String imgname;
	// 显示URL
	private String url;
	// 协议类型
	private String protocol;
	// 目的网址
	private String link;
	// 勾选此方块,你即授权Google代你调整任何你送出的图片广告
	private String accept;

	/** 付款 */
	// 上一步骤(创建关键字广告,或者图片广告)
	private String previous;

	/** 完成 */
	/**
	 * 注册页面进入执行方法
	 * 
	 * @see com.opensymphony.xwork2.ActionSupport#execute()
	 */
	@Override
	public String execute() throws Exception {
		// request.getHeader("Refener");
		if (!isStartFirst() || StringUtil.isEmpty(previous)) {
			return Action.NONE;
		}
		// 刪除廣告
		CookieUtil.deleteCookieByName(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_IMAGE);
		CookieUtil.deleteCookieByName(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_KEYWORDS);
		// 删除广告活动
		CookieUtil.deleteCookieByName(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_ACTIVITY);
		// 删除关键字列表
		CookieUtil.deleteCookieByName(request, response, Constants.COOKIE_REGISTE_KEYWORDS_LIST);
		return Action.SUCCESS;
	}

	/**
	 * 上傳圖片頁面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String uploadImage() throws Exception {
		if (!isStartFirst() || StringUtil.isEmpty(previous)) {
			return Action.NONE;
		}
		return Action.SUCCESS;
	}

	/**
	 * 用户注册执行方法(填寫基本資料)
	 * 
	 * @return
	 * @throws Exception
	 */
	public String registe() throws Exception {
		if (!isStartFirst() || StringUtil.isEmpty(previous)) {
			return Action.NONE;
		}
		// 当个人用户注册时,检验身份证号码
		if (Constants.PERSON_REGISTE.equals(type)) {
			if (!PatternUtils.match(Constants.PATTERN_IDCARD, idcard)) {
				addFieldError("idcard", getText("re.idcard.error"));
				return Action.INPUT;
			}
		} else if (Constants.ENTERPRISE_REGISTE.equals(type)) { // 企业用户注册时,检验企业统一编号
			if (!PatternUtils.match(Constants.PATTERN_COMPANY_SERIALNUMBE, serialnumber)) {
				addFieldError("serialnumber", getText("re.idcard.error"));
				return Action.INPUT;
			}
		}

		// 检验两次输入的邮箱是否一致
		if (!confirm_email.equals(email)) {
			addFieldError(Constants.CONFIRM_EMAIL, getText("re.confirm_email.error"));
			return Action.INPUT;
		}
		// 用户信息
		UserInfo user = new UserInfo();
		// 企业信息
		Company company = new Company();

		user.setAddress(address);
		user.setCity(city);
		user.setEmail(email);
		user.setFirstName(firstname);
		user.setLastName(lastname);
		user.setFullName(firstname + lastname);
		user.setFaxNum(fax);
		user.setIdCard(idcard);
		user.setMobilephone(mobile);
		user.setTelphone(phone);
		user.setZipCode(zip);
		user.setFullName(corporationname);

		JSONObject userCookie = new JSONObject(user);

		String userCookieString = userCookie.toString();
		// 存储个人基本资料
		CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_USER_INFO, userCookieString);
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_USER_INFO, user, user.getClass());
		// 个人注册
		if (Constants.PERSON_REGISTE.equals(type)) {
			// 注册类型
			user.setUserType(Constants.USER_TYPE_DB_INDIVIDUAL);
			// 存储注册类型
			CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_TYPE, Constants.USER_TYPE_DB_INDIVIDUAL);
			HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_TYPE, Constants.USER_TYPE_DB_INDIVIDUAL, Constants.USER_TYPE_DB_INDIVIDUAL.getClass());
			// 删除企业用户注册COOKIE
			CookieUtil.deleteCookieByName(request, response, Constants.COOKIE_REGISTE_COMPANY_INFO);
			HttpSessionUtils.deleteObjectFromSession(session, Constants.SESSION_REGISTE_COMPANY_INFO);
		} else if (Constants.ENTERPRISE_REGISTE.equals(type)) { // 企业用户注册时,检验企业统一编号
			// 企业名称
			company.setCompanyName(corporationname);
			// 企业统一编号
			company.setCompanyNO(serialnumber);
			// 企业对象JSON格式
			JSONObject companyCookie = new JSONObject(company);
			// 企业对象JSON格式(字符串)
			String companyCookieString = companyCookie.toString();
			// 注册类型
			user.setUserType(Constants.USER_TYPE_DB_SUPER_MANAGER);
			// 存储注册类型
			CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_TYPE, Constants.USER_TYPE_DB_SUPER_MANAGER);
			HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_TYPE, Constants.USER_TYPE_DB_SUPER_MANAGER, Constants.USER_TYPE_DB_SUPER_MANAGER.getClass());
			// 存储企业用户注册信息COOKIE
			CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_COMPANY_INFO, companyCookieString);
			HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_COMPANY_INFO, company, company.getClass());
		}
		this.previous = "userDetail";
		return Action.SUCCESS;
	}

	/**
	 * 頁面跳轉檢查
	 * 
	 * @return
	 * @throws Exception
	 */
	public boolean isStartFirst() throws Exception {
		String startFirst = (String) HttpSessionUtils.getObjectFromSession(session, Constants.SESSION_START_FIRST);
		if (StringUtil.isNull(startFirst))
			return false;
		return true;
	}

	/**
	 * 创建关键字广告
	 * 
	 * @return
	 * @throws Exception
	 */
	public String createKeywordsAdvertisement() throws Exception {
		if (!isStartFirst() || StringUtil.isEmpty(previous)) {
			return Action.NONE;
		}
		this.previous = "keword";
		// 如果输入每月预算,验证其是否是数字
		if (!StringUtil.isEmpty(costPerMonth) && !PatternUtils.match(Constants.PATTERN_COMPANY_INTEGER, costPerMonth)) {
			addFieldError("costPerMonth", getText("re.costPerMonth.error"));
			return Action.INPUT;
		}
		// 如果选择自定义每日预算,验证输入的每日预算金额是否是数字
		if (CUSTOM_BUDGET_ON.equals(budget.toUpperCase())) {
			if (!PatternUtils.match(Constants.PATTERN_COMPANY_INTEGER, customBudget)) {
				addFieldError("customBudget", getText("re.customBudget.error"));
				return Action.INPUT;
			} else {
				// 设置每日预算为自定义的预算
				this.budget = this.customBudget;
			}
		}
		// 关键字广告
		KeywordsAdvInfo keywordsAdvertisement = new KeywordsAdvInfo();
		/************************* 构建关键字广告 Start ******************************/
		// 内容描述
		keywordsAdvertisement.setContent(desc);
		// 宣传网址
		keywordsAdvertisement.setHref(weblink);
		// 广告标题
		keywordsAdvertisement.setTitle(title);
		/************************* 构建关键字广告 End ******************************/
		// 关键字列表
		List<Keywords> keywordList = new ArrayList<Keywords>();
		// 分割keywords
		String[] keys = keywords.split("\\s+");
		// 构建关键字列表
		for (String key : keys) {
			// 关键字对象
			Keywords keywordItem = new Keywords();
			// 关键字
			keywordItem.setKeywords(key);
			logger.info(key);
			// 将此关键字加入关键字列表
			keywordList.add(keywordItem);
		}
		// 广告活动
		AdvActivity activity = new AdvActivity();
		// 广告活动名称
		activity.setActivityName("我的广告活动");
		// 每日预算
		activity.setMaxPayPerDay(Double.valueOf(budget));
		if (!StringUtil.isEmpty(costPerMonth)) {
			// 每月预算
			activity.setCostPerMonth(Double.valueOf(costPerMonth));
		}

		// 保存广告活动
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_ADVERTISEMENT_ACTIVITY, activity, activity.getClass());
		CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_ACTIVITY, new JSONObject(activity).toString());
		// 保存关键字广告
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_ADVERTISEMENT_KEYWORDS, keywordsAdvertisement, keywordsAdvertisement.getClass());
		CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_KEYWORDS, new JSONObject(keywordsAdvertisement).toString());
		// 保存关键字列表
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_KEYWORDS_LIST_INFO, keywordList, keywordList.getClass());
		CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_KEYWORDS_LIST, new JSONArray(keys).toString());
		// 返回SUCCESS
		return Action.SUCCESS;
	}

	/**
	 * 创建图片广告
	 * 
	 * @return
	 * @throws Exception
	 */
	public String createImgAdvertisement() throws Exception {
		if (!isStartFirst() || StringUtil.isEmpty(previous)) {
			return Action.NONE;
		}
		if (uploadimg == null) {
			addFieldError("uploadimg", getText("re.uploadimg.error"));
			return Action.INPUT;
		}
		if (!isURL(url, "url")) {
			return Action.INPUT;
		}
		if (!isURL(link, "link")) {
			return Action.INPUT;
		}
		// 获取文件配置
		ResourceBundle rb = ResourceBundle.getBundle(FILE_CONFIG_NAME);
		// 获取文件上传保存路径配置
		String saveDir = rb.getString(FILE_SAVE_DIR);
		// 获取保存路径
		String uploadDir = ServletActionContext.getServletContext().getRealPath(saveDir);
		// 创建路径
		File directory = new File(uploadDir);
		// 路径不存在时
		if (!directory.exists()) {
			// 创建不存在路径
			directory.mkdirs();
		}
		// 新建需要保存的新文件
		File dest = new File(uploadDir + "/" + uploadimgFileName);
		// 将上传文件保存至配置路径
		uploadimg.renameTo(dest);
		// 上次页面Action
		this.previous = "img";
		// 新建图片广告
		HyperlinkAdvInfo imgAd = new HyperlinkAdvInfo();

		// 新建廣告位置對象
		AdvPosition advPosition = new AdvPosition();
		// 廣告位置
		advPosition.setPosition(position);
		// 價格
		advPosition.setPrice(0D);

		// 广告显示名称
		imgAd.setAdvName(imgname);
		// 开始日期
		imgAd.setBeginTime(DateUtils.getDateString(new Date(), null));
		// 有效日期
		imgAd.setEndTime(todate);
		// 链接地址
		imgAd.setHref(protocol + link);
		// 显示URL
		imgAd.setURL(Constants.HTTP + url);
		// 图片路径
		imgAd.setSrc(saveDir + "/" + uploadimgFileName);
		// 图片位置
		imgAd.setPosition(position);
		// 保存图片广告
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_REGISTE_ADVERTISEMENT_IMAGE, imgAd, imgAd.getClass());
		CookieUtil.addCookie(request, response, Constants.COOKIE_REGISTE_ADVERTISEMENT_IMAGE, new JSONObject(imgAd).toString());
		return Action.SUCCESS;
	}

	/**
	 * 進入註冊頁面
	 * 
	 * @return
	 * @throws Exception
	 */
	public String goRegiste() throws Exception {
		// 表示正常進入
		HttpSessionUtils.copyObjectToSession(session, Constants.SESSION_START_FIRST, Constants.YES, Constants.YES.getClass());
		this.previous = "goRegiste";
		// 返回
		return Action.SUCCESS;
	}

	/**
	 * 判断一字符串是非URL
	 * 
	 * @param url
	 * @param fieldName
	 * @return
	 */
	private boolean isURL(String url, String fieldName) {
		try {
			if (StringUtil.isEmpty(url)) {
				addFieldError(fieldName, getText("re." + fieldName + ".error"));
				return false;
			}
			new URL(Constants.HTTP + url);
		} catch (Exception e) {
			addFieldError(fieldName, getText("re." + fieldName + ".error"));
			return false;
		}
		return true;
	}

	/**
	 * @return the previous
	 */
	public String getPrevious() {
		return previous;
	}

	/**
	 * @param previous
	 *            the previous to set
	 */
	public void setPrevious(String previous) {
		this.previous = previous;
	}

	/**
	 * @return the fax
	 */
	public String getFax() {
		return fax;
	}

	/**
	 * @param fax
	 *            the fax to set
	 */
	public void setFax(String fax) {
		this.fax = fax;
	}

	/**
	 * @return the type
	 */
	public String getType() {
		return type;
	}

	/**
	 * @param type
	 *            the type to set
	 */
	public void setType(String type) {
		this.type = type;
	}

	/**
	 * @return the idcard
	 */
	public String getIdcard() {
		return idcard;
	}

	/**
	 * @param idcard
	 *            the idcard to set
	 */
	public void setIdcard(String idcard) {
		this.idcard = idcard;
	}

	/**
	 * @return the confirm_email
	 */
	public String getConfirm_email() {
		return confirm_email;
	}

	/**
	 * @param confirm_email
	 *            the confirm_email to set
	 */
	public void setConfirm_email(String confirm_email) {
		this.confirm_email = confirm_email;
	}

	/**
	 * @return the firstname
	 */
	public String getFirstname() {
		return firstname;
	}

	/**
	 * @param firstname
	 *            the firstname to set
	 */
	public void setFirstname(String firstname) {
		this.firstname = firstname;
	}

	/**
	 * @return the lastname
	 */
	public String getLastname() {
		return lastname;
	}

	/**
	 * @param lastname
	 *            the lastname to set
	 */
	public void setLastname(String lastname) {
		this.lastname = lastname;
	}

	/**
	 * @return the email
	 */
	public String getEmail() {
		return email;
	}

	/**
	 * @param email
	 *            the email to set
	 */
	public void setEmail(String email) {
		this.email = email;
	}

	/**
	 * @return the phone
	 */
	public String getPhone() {
		return phone;
	}

	/**
	 * @param phone
	 *            the phone to set
	 */
	public void setPhone(String phone) {
		this.phone = phone;
	}

	/**
	 * @return the mobile
	 */
	public String getMobile() {
		return mobile;
	}

	/**
	 * @param mobile
	 *            the mobile to set
	 */
	public void setMobile(String mobile) {
		this.mobile = mobile;
	}

	/**
	 * @return the serialnumber
	 */
	public String getSerialnumber() {
		return serialnumber;
	}

	/**
	 * @param serialnumber
	 *            the serialnumber to set
	 */
	public void setSerialnumber(String serialnumber) {
		this.serialnumber = serialnumber;
	}

	/**
	 * @return the corporationname
	 */
	public String getCorporationname() {
		return corporationname;
	}

	/**
	 * @param corporationname
	 *            the corporationname to set
	 */
	public void setCorporationname(String corporationname) {
		this.corporationname = corporationname;
	}

	/**
	 * @return the city
	 */
	public String getCity() {
		return city;
	}

	/**
	 * @param city
	 *            the city to set
	 */
	public void setCity(String city) {
		this.city = city;
	}

	/**
	 * @return the address
	 */
	public String getAddress() {
		return address;
	}

	/**
	 * @param address
	 *            the address to set
	 */
	public void setAddress(String address) {
		this.address = address;
	}

	/**
	 * @return the zip
	 */
	public String getZip() {
		return zip;
	}

	/**
	 * @param zip
	 *            the zip to set
	 */
	public void setZip(String zip) {
		this.zip = zip;
	}

	/**
	 * @return the customBudget
	 */
	public String getCustomBudget() {
		return customBudget;
	}

	/**
	 * @param customBudget
	 *            the customBudget to set
	 */
	public void setCustomBudget(String customBudget) {
		this.customBudget = customBudget;
	}

	/**
	 * @return the budget
	 */
	public String getBudget() {
		return budget;
	}

	/**
	 * @param budget
	 *            the budget to set
	 */
	public void setBudget(String budget) {
		this.budget = budget;
	}

	/**
	 * @return the costPerMonth
	 */
	public String getCostPerMonth() {
		return costPerMonth;
	}

	/**
	 * @param costPerMonth
	 *            the costPerMonth to set
	 */
	public void setCostPerMonth(String costPerMonth) {
		this.costPerMonth = costPerMonth;
	}

	/**
	 * @return the weblink
	 */
	public String getWeblink() {
		return weblink;
	}

	/**
	 * @param weblink
	 *            the weblink to set
	 */
	public void setWeblink(String weblink) {
		this.weblink = weblink;
	}

	/**
	 * @return the title
	 */
	public String getTitle() {
		return title;
	}

	/**
	 * @param title
	 *            the title to set
	 */
	public void setTitle(String title) {
		this.title = title;
	}

	/**
	 * @return the desc
	 */
	public String getDesc() {
		return desc;
	}

	/**
	 * @param desc
	 *            the desc to set
	 */
	public void setDesc(String desc) {
		this.desc = desc;
	}

	/**
	 * @return the keywords
	 */
	public String getKeywords() {
		return keywords;
	}

	/**
	 * @param keywords
	 *            the keywords to set
	 */
	public void setKeywords(String keywords) {
		this.keywords = keywords;
	}

	/**
	 * @return the position
	 */
	public String getPosition() {
		return position;
	}

	/**
	 * @param position
	 *            the position to set
	 */
	public void setPosition(String position) {
		this.position = position;
	}

	/**
	 * @return the uploadimg
	 */
	public File getUploadimg() {
		return uploadimg;
	}

	/**
	 * @param uploadimg
	 *            the uploadimg to set
	 */
	public void setUploadimg(File uploadimg) {
		this.uploadimg = uploadimg;
	}

	/**
	 * @return the uploadimgFileName
	 */
	public String getUploadimgFileName() {
		return uploadimgFileName;
	}

	/**
	 * @param uploadimgFileName
	 *            the uploadimgFileName to set
	 */
	public void setUploadimgFileName(String uploadimgFileName) {
		this.uploadimgFileName = uploadimgFileName;
	}

	/**
	 * @return the uploadimgContentType
	 */
	public String getUploadimgContentType() {
		return uploadimgContentType;
	}

	/**
	 * @param uploadimgContentType
	 *            the uploadimgContentType to set
	 */
	public void setUploadimgContentType(String uploadimgContentType) {
		this.uploadimgContentType = uploadimgContentType;
	}

	/**
	 * @return the todate
	 */
	public String getTodate() {
		return todate;
	}

	/**
	 * @param todate
	 *            the todate to set
	 */
	public void setTodate(String todate) {
		this.todate = todate;
	}

	/**
	 * @return the imgname
	 */
	public String getImgname() {
		return imgname;
	}

	/**
	 * @param imgname
	 *            the imgname to set
	 */
	public void setImgname(String imgname) {
		this.imgname = imgname;
	}

	/**
	 * @return the url
	 */
	public String getUrl() {
		return url;
	}

	/**
	 * @param url
	 *            the url to set
	 */
	public void setUrl(String url) {
		this.url = url;
	}

	/**
	 * @return the protocol
	 */
	public String getProtocol() {
		return protocol;
	}

	/**
	 * @param protocol
	 *            the protocol to set
	 */
	public void setProtocol(String protocol) {
		this.protocol = protocol;
	}

	/**
	 * @return the link
	 */
	public String getLink() {
		return link;
	}

	/**
	 * @param link
	 *            the link to set
	 */
	public void setLink(String link) {
		this.link = link;
	}

	/**
	 * @return the accept
	 */
	public String getAccept() {
		return accept;
	}

	/**
	 * @param accept
	 *            the accept to set
	 */
	public void setAccept(String accept) {
		this.accept = accept;
	}

	/**
	 * @return the userService
	 */
	public IUserService getUserService() {
		return userService;
	}

	/**
	 * @param userService
	 *            the userService to set
	 */
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
}